<?php

namespace App\Common\Eloquent\Model;

use Illuminate\Support\Facades\Cache as X;

/**
 * Model缓存：获取产品的时，更新缓存（mfn缓存和id缓存）；更新产品时（改、删），清除缓存。
 *
 * @package App\Contract\Eloquent\Model
 */
trait Cache
{

    use \App\Common\Cache;

    protected static function no_cache (array $key):array
    {
        return array_diff(
            $key,
            array_keys(self::get_cache_ls($key))
        );
    }

    protected static function get_cache_ls (array $key)
    {
        $key = array_combine($key, $key);
        foreach ($key as $i=>&$id) {
            if (!$id = self::cache($id)) {
                unset ($key[$i]);
            }
        }
        return $key;
    }



    protected static function primary_key ()
    {
        return (new static)->primaryKey;
    }


    private static function cache_where_test ($where=[])
    {
        if ($where) {
//            $res->where($where);
            foreach ($where as $k=>&$v) {
                $v = $k.'='.$v;
            }
            $where = join('&', $where);
        } else {
            $where = '';
        }
    }


    /**
     * 查找商品并自动缓存
     * @param $mfn int|array
     * @return object|null
     * */
    static function findWithCache ($id, $key='')
    {
        $key = $key ?: self::primary_key();

        $arr = is_array($id) ? $id : [$id];

        // 找出无缓存的产品加入缓存
        if ($res = self::no_cache($arr) ) {
            $res = static::query()->whereIn($key, $res)->get();
            foreach ($res as &$model) {
                self::cache($model->$key, $model, property_exists(static::class, 'model_cache') ? static::$model_cache : 0);
            }
        }

        // 统一返回缓存数据
        $res = self::get_cache_ls($arr);
        return is_array($id) ? collect($res) : @$res[$id];

    }


}
